const express = require('express');
const router = express.Router();
const axios = require('axios');
const mysql = require('mysql');

const connection = mysql.createConnection({
  host: '127.0.0.1',
  user: 'root',
  password: '123456',
  database: 'bdzy_video',
});
connection.connect();

// 正则替换字符
function toLiteral(str) {
  var dict = { '\b': 'b', '\t': 't', '\n': 'n', '\v': 'v', '\f': 'f', '\r': 'r' };
  return str.replace(/([\\'"\b\t\n\v\f\r])/g, function ($0, $1) {
    return '\\' + (dict[$1] || $1);
  });
}

let pageCount = 0; //总页数
/* GET home page. */
router.get('/', function (req, res, next) {
  axios({
    method: 'get',
    url: 'https://m3u8.apibdzy.com/api.php/provide/vod/?ac=list',
  }).then((res) => {
    pageCount = res.data.pagecount;
    // 循环分页，获取数据
    for (let i = 1; i < pageCount + 1; i++) {
      console.log(i, '---', new Date());
      getVideoList(i);
    }
  });
  res.send('采集数据');
});

// 获取每一页资源数据
async function getVideoList(page) {
  try {
    // 开始采集视频
    // console.log('1.请求数据中.....');
    const response = await axios({
      method: 'get',
      url: `https://m3u8.apibdzy.com/api.php/provide/vod/?ac=list&pg=${page}`,
    }).then((res) => {
      // console.log('2.返回请求结果...');
      insertVideo(res.data.list, page);
    });
  } catch (error) {
    console.error(error);
  }
}
// 将资源数据写入数据库
async function insertVideo(list, page) {
  // console.log(`3.写入数据库....`);
  for (let i = 0; i < list.length; i++) {
    let current = list[i];
    // 如果数据库中不存在这一项，则写入
    let sql = `SELECT * FROM video WHERE vod_id = ${current.vod_id}`;
    connection.query(sql, (err, data) => {
      if (err) {
        console.log('err!', err);
      } else {
        if (JSON.parse(JSON.stringify(data)).length === 0) {
          // console.log('不存在');
          let addVideoSql = `INSERT INTO video ( type_id,type_name,vod_id,vod_name,vod_play_from,vod_remarks,vod_time ) VALUES ( ${current.type_id},'${toLiteral(current.type_name)}',${current.vod_id},'${toLiteral(current.vod_name)}','${toLiteral(current.vod_play_from)}','${toLiteral(current.vod_remarks)}','${toLiteral(current.vod_time)}' );`;
          connection.query(addVideoSql, (err, data) => {
            if (err) {
              console.log('写入出错了!', err);
            } else {
              // console.log('写入成功！', JSON.stringify(data));
            }
          });
        } else {
          // console.log('存在');
        }
      }
    });
  }
  if (page === pageCount) {
    console.log('4.写入完毕...断开链接');
    connection.end();
  }
}
module.exports = router;
